package cc.linker.steplink.crm.merchant.service.impl;

import cc.linker.steplink.crm.commons.constant.TlPayConstant;
import cc.linker.steplink.crm.commons.constant.WcPayConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.model.WcPayProperties;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.commons.yzj.YzjRequest;
import cc.linker.steplink.crm.merchant.dao.ShopGoodsMapper;
import cc.linker.steplink.crm.merchant.dao.acs.MerchantInfoDao;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.merchanth5.service.MaiBaoLaService;
import cc.linker.steplink.crm.merchanth5.service.common.SmsService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class MerchantInfoServiceImpl implements MerchantInfoService {

    @Autowired
    private MerchantInfoDao MerchantInfoDao;
    @Autowired
    private WcPayProperties wcPayProperties;
    @Autowired
    private HttpService httpService;
    @Autowired
    private MaiBaoLaService maiBaoLaService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private ShopGoodsMapper shopGoodsMapper;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CommonsService commonsService;
    @Autowired
    private YzjRequest yzjRequest;

    /**
     * 获取商家信息
     *
     * @param param
     * @return
     */
    @Override
    public Map<String, Object> getMerchantInfo(Map<String, Object> param) {
        return MerchantInfoDao.getMerchantInfo(param);
    }

    /**
     * 上传资质
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> saveMerchantInfo(Map<String, Object> params) throws Exception {
        Map<String, Object> res = new HashMap<>();
        String oldId = "";
        if (params.containsKey("id") && !StringUtil.isEmpty(params.get("id").toString())) {
            // 判断当前记录是否已审核过
            oldId = params.get("id").toString();
            Map info = MerchantInfoDao.getMerchantInfoById(params.get("id").toString());
            if ("0".equals(info.get("checkStatus"))) {
                // 更新
                if (!MerchantInfoDao.updateInfo(params)) {
                    throw new GlobalException(new ResponseException(400, "保存失败"));
                }
                res.put("id", params.get("id").toString());
                res.put("oldId", oldId);
                return res;
            }
        }
        // 新增
        String id = UUID.randomUUID().toString();
        params.put("id", id);
        if (!MerchantInfoDao.addInfo(params)) {
            throw new GlobalException(new ResponseException(400, "保存失败"));
        }
        res.put("id", id);
        res.put("oldId", StringUtils.isEmpty(oldId) ? id : oldId);

        //修改添加删除redis的缓存信息
        String merchantId = params.containsKey("customerId") ? params.get("customerId").toString() : "";
        String orgId = params.get("orgId").toString();
        stringRedisTemplate.delete("merchant:merchant_info_" + (!StringUtils.isEmpty(merchantId) ? merchantId : orgId));
        return res;
    }

    /**
     * 获取客户id 根据adminId
     *
     * @param adminId
     * @return
     */
    @Override
    public String getCustomerIdByAdminId(String adminId) {
        return MerchantInfoDao.getCustomerIdByAdminId(adminId);
    }

    /**
     * 提交审核
     *
     * @return
     */
    @Override
    public Boolean submitAudit(Map<String, Object> params) throws Exception {
        String keys = "merchantInfo_" + params.get("id").toString();
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(keys, "1", 10, TimeUnit.SECONDS);
        if (StringUtils.isEmpty(aBoolean)) {
            // 设置
            throw GlobalException.build("审核中，请勿重复提交");
        }
        // 判断 当前通联审核状态
        String oldStatus = MerchantInfoDao.getVerifyStatusById(params.get("id").toString());
        if ("4".equals(oldStatus)) {
            throw GlobalException.build("通联审核中，请勿重复提交");
        } else if ("2".equals(oldStatus)) {
            throw GlobalException.build("审核已通过，请勿重复提交");
        }

        //待审核状态
        MerchantInfoDao.submitAudit(params);
        //判断是联盟商家还是大麦 根据ID 查找customerId是否为空
        Boolean ifSaler = MerchantInfoDao.ifSalerById(params.get("id").toString());
        Map<String, Object> temp = new HashMap<>();
        if (ifSaler) {
            //联盟商家 更新联盟商家表审核状态
            temp.put("adminId", params.get("adminId").toString());
            temp.put("state", "2");
            MerchantInfoDao.updateSalerStatus(temp);
        } else {
            //大麦开户 判断后台是否开启自动审核
            Boolean autoCheck = MerchantInfoDao.getAutoCheckStatus();
            String status = params.get("checkStatus").toString();
            String backReason = "";
            if (autoCheck != null && autoCheck) {
                status = "4";
                JSONObject object = openPayAccount(params.get("id").toString());
                if (object != null) {
                    if (("200").equals(object.getString("code"))) {
                        String statusCode = object.getJSONObject("data").getString("status");
                        if ("30".equals(statusCode)) {
                            status = "2";
                        } else if ("40".equals(statusCode)) {
                            status = "3";
                        } else if ("50".equals(statusCode)) {
                            status = "3";
                            backReason = "上传通联ftp失败";
                        }
                    }
                }
            }
            temp.put("status", status);
            temp.put("backReason", backReason);
            temp.put("id", params.get("id"));
            MerchantInfoDao.doVerify(temp);
        }
        stringRedisTemplate.delete(keys);
        return true;
    }

    @Override
    public List<Map<String, Object>> getSalerPromoterList(Map<String, Object> param) {
        return MerchantInfoDao.getSalerPromoterList(param);
    }

    @Override
    public Long getTotalBackFee(String customerId, String orgId) {
        return MerchantInfoDao.getTotalBackFee(customerId, orgId);
    }

    @Override
    public Long getSonTotalBackFee(String pcustomerId, String customerId, String orgId) {
        return MerchantInfoDao.getSonTotalBackFee(pcustomerId, customerId, orgId);
    }

    @Override
    public Long getUserTotalCash(String customerId, String orgId) {
        return MerchantInfoDao.getUserTotalCash(customerId, orgId);
    }

    @Override
    public Long getUserTotalFailCash(String customerId, String orgId) {
        return MerchantInfoDao.getUserTotalFailCash(customerId, orgId);
    }

    @Override
    public Map<String, Object> getWallet(String adminId, String orgId, Boolean ifSaler) {
        if (ifSaler) {
            //小b
            return MerchantInfoDao.getXbWallet(adminId);
        } else {
            //大麦
            return MerchantInfoDao.getDmWallet(orgId);
        }
    }

    @Override
    public String getUserTypeByAdminId(String adminId) {
        return MerchantInfoDao.getUserTypeByAdminId(adminId);
    }

    @Override
    public List<Map<String, Object>> getVerifyList(String orgId, String userType) {
        if ("1".equals(userType)) {
            //联汇科技超级管理员  审核大麦列表
            return MerchantInfoDao.getDmVerify();
        } else {
            // 审核联盟商城
            return MerchantInfoDao.getSalerVerify(orgId);
        }
    }

    @Override
    public Map<String, Object> getVerifyInfo(String id, String customerId) {
        if (StringUtil.isEmpty(id)) {
            return MerchantInfoDao.getVerifyInfoByCid(customerId);
        } else {
            return MerchantInfoDao.getVerifyInfo(id);
        }
    }

    @Override
    public Boolean doVerifyInfo(Map<String, Object> params) throws Exception {
        String keys = "merchantInfoVerify_" + params.get("id").toString();
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(keys, "1", 10, TimeUnit.SECONDS);
        if (StringUtils.isEmpty(aBoolean)) {
            // 设置
            throw GlobalException.build("审核中，请勿重复提交");
        }
        String orgId = (String) params.get("orgId");
        // 判断 当前通联审核状态
        String oldStatus = MerchantInfoDao.getVerifyStatusById(params.get("id").toString());
        if ("4".equals(oldStatus)) {
            throw GlobalException.build("通联审核中，请勿重复提交");
        } else if ("2".equals(oldStatus)) {
            throw GlobalException.build("审核已通过，请勿重复提交");
        }
        // 审核通过的情况 提交中金开通账户 大麦 联盟商家
        if ("2".equals(params.get("status").toString())) {
            JSONObject object = openPayAccount(params.get("id").toString());
            String status = "4";
            String backReason = "";
            if (object != null) {
                if (("200").equals(object.getString("code"))) {
                    String statusCode = object.getJSONObject("data").getString("status");
                    if ("30".equals(statusCode)) {
                        status = "2";
                    } else if ("40".equals(statusCode)) {
                        status = "3";
                    } else if ("50".equals(statusCode)) {
                        status = "3";
                        backReason = "上传通联ftp失败";
                    }
                }
            }
            params.put("backReason", backReason);
            params.put("status", status);
        } else if ("3".equals(params.get("status").toString())) {
            String id = params.get("id").toString();
            //打回需要发送短信
            Map infoMap = MerchantInfoDao.getVerifyInfo(id);
            Object legalPersonPhoneObj = infoMap.get("legalPersonPhone");
            if (params.get("backReason") != null && legalPersonPhoneObj != null) {
                String paramsString = "{\"reason\":\"" + params.get("backReason").toString() + "\"}";
                Map<String, Object> nvps = new HashMap<>();
                nvps.put("businessType", "9006");
                nvps.put("mobilNumber", legalPersonPhoneObj.toString());
                nvps.put("params", paramsString);
                nvps.put("token", null);
                smsService.sendVerification(orgId, nvps);
            }
        }
        if (!"1".equals(params.get("userType").toString())) {
            // 审核联盟商城 有cid
            Map<String, Object> temp = MerchantInfoDao.getMerchantInfoById(params.get("id").toString());
            temp.put("state", "2".equals(params.get("status").toString()) ? "1" : "0");
            temp.put("goodsStatus", "2".equals(params.get("status").toString()) ? 1 : 0);
            // 更新联盟商家表 认证状态
            MerchantInfoDao.updateSalerStatus(temp);
        }
        // 更新审核状态
        MerchantInfoDao.doVerify(params);
        stringRedisTemplate.delete(keys);
        return true;
    }

    /**
     * 调用中金开户接口
     *
     * @return
     */
    private JSONObject openPayAccount(String id) throws Exception {
        Map<String, Object> temp = MerchantInfoDao.getVerifyInfo(id);
        if ("2".equals(temp.get("checkStatus"))) {
            throw GlobalException.build("该商家已通过审核，请勿重复提交");
        }
        Map<String, Object> map = new HashMap<>();
        String orgId = "";
        if (!StringUtils.isEmpty(temp.get("orgId"))) {
            orgId = temp.get("orgId").toString();
        }
        String allLicenceExpiryDate = "";
        if (!StringUtils.isEmpty(temp.get("businessTermEnd"))) {
            allLicenceExpiryDate = temp.get("businessTermEnd").toString().substring(0, 10);
        }
        map.put("accountType", 0);
        map.put("allLicenceExpiryDate", allLicenceExpiryDate);
        map.put("authCapital", temp.get("registeredCapital"));
        // 获取资金账户名称
        String bankAccountName = MerchantInfoDao.getBankAccountName(orgId);
        map.put("bankAccountName", bankAccountName == null ? "" : bankAccountName);
        map.put("bankAccountNo", temp.get("publicAccount"));
        map.put("basicAcctNo", temp.get("businessBase"));
        map.put("branchName", temp.get("publicBankBranch"));
        map.put("businessScope", temp.get("businessScope"));
        map.put("categoryType", temp.get("businessTaxonomy"));
        map.put("city", temp.get("cityName"));

        Integer payMode = MerchantInfoDao.getPayModeByOrgId(orgId);
        if (payMode == 2 || payMode == 3) {
            String alias = "";
            if (payMode == 3) {
                alias = maiBaoLaService.getAliasByLinker();
            }
            if (payMode == 2) {
                alias = maiBaoLaService.getAlias(orgId);
            }
            map.put("clintType", alias);
        }
        map.put("corAddress", temp.get("businessAddress"));
        map.put("corEmail", temp.get("businessEmail"));
        map.put("corporationName", temp.get("businessName"));
        map.put("corporationShort", temp.get("businessAbbreviation"));
        map.put("credentialNumber", temp.get("passportNumber"));
        map.put("customerAddress", temp.get("address"));
        map.put("customerEmail", temp.get("legalPersonEmail"));
        // 用户ID（个人/法人ID） todo
//        String customerId = ("1".equals(temp.get("type")))?
//                Constants.DM_PREFIX.concat(temp.get("orgId").toString()):
//                Constants.XB_PREFIX.concat(temp.get("customerId").toString());
        String customerId = "";
        if (!StringUtils.isEmpty(temp.get("id"))) {
            customerId = temp.get("id").toString();
        }
        map.put("customerId", customerId);
        map.put("customerName", temp.get("legalPersonName") != null ? temp.get("legalPersonName").toString() : "");
        map.put("customerPhone", temp.get("legalPersonPhone") != null ? temp.get("legalPersonPhone").toString() : "");
        map.put("customerType", "12");
        String expiryDate = "";
        if (!StringUtils.isEmpty(temp.get("passportTermEnd"))) {
            expiryDate = temp.get("passportTermEnd").toString().substring(0, 10).replaceAll("-", "");
        }
        map.put("expiryDate", expiryDate);
        // 通用行业代码
        String industry = "";
        if (!StringUtils.isEmpty(temp.get("businessGeneralIndustryCode"))) {
            industry = temp.get("businessGeneralIndustryCode").toString();
            int firstIndex = industry.lastIndexOf(":");
            int lastIndex = industry.lastIndexOf("\"");
            industry = industry.substring(firstIndex + 2, lastIndex);
        }
        map.put("industry", industry);
        map.put("industryBelongType", temp.get("businessIndustryCode") != null ? temp.get("businessIndustryCode").toString() : "");
        map.put("institutionID", "005402");
        String issDate = "";
        if (!StringUtils.isEmpty(temp.get("passportTermStart"))) {
            issDate = temp.get("passportTermStart").toString().substring(0, 10).replaceAll("-", "");
        }
        map.put("issDate", issDate);
        map.put("merchantAppid", "");
        map.put("orgId", orgId);
        map.put("parentBankName", temp.get("publicBank") != null ? temp.get("publicBank").toString() : "");
        map.put("province", temp.get("provinceName") != null ? temp.get("provinceName").toString() : "");
        map.put("scale", temp.get("businessScale") != null ? temp.get("businessScale").toString() : "");
        map.put("source", "2");
        map.put("unifiedSocialCreditCode", temp.get("socialCreditCode") != null ? temp.get("socialCreditCode").toString() : "");
        map.put("unifiedSocialCreditUrl", temp.get("socialCreditImage") != null ? temp.get("socialCreditImage").toString() : "");
        map.put("licenceUrl", temp.get("licenceUrl") != null ? temp.get("licenceUrl").toString() : "");
        map.put("unionBank", temp.get("publicBankCode") != null ? temp.get("publicBankCode").toString() : "");

        //请求中金
        LOGGER.info("调用参数" + map);
        String string = JSON.toJSONString(map);
        String resultOpen = httpService.doPost(wcPayProperties.getAcsurl() + TlPayConstant.USER_OPEN_PAY_ACCOUNT, string, WcPayConstant.JSON);
        JSONObject object = JSONObject.parseObject(resultOpen);
        LOGGER.info("调用结果" + object.toJSONString());
        // 上传通联 ftp
        if (payMode == 2 || payMode == 3) {
            /**********更换上传接口**********/
            String alias = "";
            if (payMode == 3) {
                alias = maiBaoLaService.getAliasByLinker();
            }
            if (payMode == 2) {
                alias = maiBaoLaService.getAlias(orgId);
            }
            Map<String, Object> req = new HashMap<>();
            //调试用"yth"
            req.put("clintType", alias);
            req.put("customerId", id);
            String url = wcPayProperties.getAcsurl() + TlPayConstant.COMMON_UPLOADPICTURE;
            List<Map<String, Object>> fileList = new ArrayList<>();
            Map<String, Object> settlement = new HashMap<>();
            settlement.put("picture", commonsService.encodeImageToBase64(temp.get("licenceUrl").toString()));
            settlement.put("picType", 4);
            Map<String, Object> license = new HashMap<>();
            license.put("picture", commonsService.encodeImageToBase64(temp.get("socialCreditImage").toString()));
            license.put("picType", 5);
            fileList.add(settlement);
            fileList.add(license);
            req.put("picList", fileList);
            String result;
            try {
                LOGGER.info("callTlAndReturn,request===[{}]", JSON.toJSONString(req));
                result = httpService.doPost(url, JSON.toJSONString(req), WcPayConstant.JSON);
            } catch (URISyntaxException | IOException e) {
                throw GlobalException.build("网关调用异常");
            }
            LOGGER.info(result);
            if (!StringUtils.isEmpty(result)) {
                Map<String, Object> res = (Map<String, Object>) JSON.parse(result);
                if (!"200".equals(res.get("code").toString())) {
                    throw GlobalException.build("上传失败");
                } else {
                    Map<String, Object> da = (Map<String, Object>) JSON.parse(res.get("data").toString());
                    if (!"30".equals(da.get("status").toString())) {
                        throw GlobalException.build("上传失败");
                    }
                }
            }
            /**********更换上传接口**********/

            // 组装上传数据
            // 获取ftp账号信息
//            Map<String, Object> ftpInfo = new HashMap<>();
//            if(payMode == 2){
//                ftpInfo = MerchantInfoDao.getFtpInfoByOrgId(orgId);
//            }else{
//                ftpInfo = MerchantInfoDao.getFtpInfoByOrgId("linker");
//            }
//            String ftpServerIp = ftpInfo.get("ftpServerIp").toString();
//            Integer ftpServerPort = Integer.parseInt(ftpInfo.get("ftpServerPort").toString());
//            String ftpAccount = ftpInfo.get("ftpAccount").toString();
//            String ftpPassword = ftpInfo.get("ftpPassword").toString();
//            List<Map<String, Object>> fileList = new ArrayList<>();
//            Map<String, Object> settlement = new HashMap<>();
//            settlement.put("fileUrl", temp.get("licenceUrl").toString());
//            settlement.put("fileName", "bank_settlement.jpg");
//            Map<String, Object> license = new HashMap<>();
//            license.put("fileUrl", temp.get("socialCreditImage").toString());
//            license.put("fileName", "business_license.jpg");
//            Map<String, Object> cerificateBack = new HashMap<>();
//            cerificateBack.put("fileUrl", temp.get("passportImageOff").toString());
//            cerificateBack.put("fileName", "legal_cerificate_back.jpg");
//            Map<String, Object> cerificateFront = new HashMap<>();
//            cerificateFront.put("fileUrl", temp.get("passportImageOn").toString());
//            cerificateFront.put("fileName", "legal_cerificate_front.jpg");
//            fileList.add(settlement);
//            fileList.add(license);
//            fileList.add(cerificateBack);
//            fileList.add(cerificateFront);
//            // 调用ftp上传方法
//            boolean uploadStatus = FTPUtil.uploadFtp(ftpServerIp, ftpServerPort, ftpAccount, ftpPassword, id, fileList);
//            if (!uploadStatus) {
//                // 上传失败返回结果
//                String info = "{\"code\":200,\"data\":{\"status\":50}}";
//                return JSONObject.parseObject(info);
//            }
        }
        return object;
    }

    @Override
    public Boolean getAutoCheckStatus() {

        if (null == MerchantInfoDao.getAutoCheckStatus()) {
            MerchantInfoDao.addAutoCheckStatus();
        }
        return MerchantInfoDao.getAutoCheckStatus();
    }

    @Override
    public Boolean changeAutoCheckStatus(Map<String, Object> params) {
        return MerchantInfoDao.changeAutoCheckStatus(params);
    }

    @Override
    public String getBusCert(Map<String, Object> params) {
        return MerchantInfoDao.getBusCert(params);
    }

    @Override
    public Map<String, Object> getDetail(Map<String, Object> param) {
        return MerchantInfoDao.getDetail(param);
    }

    @Override
    public Map<String, Object> getInfoByCid(String customerId) {
        return MerchantInfoDao.getInfoByCid(customerId);
    }

    @Override
    public Map<String, Object> getInfoByOid(String orgId) {
        return MerchantInfoDao.getInfoByOid(orgId);
    }

    @Override
    public Boolean getPayStatus(String orgId) {
        return MerchantInfoDao.getPayStatus(orgId);
    }

    @Override
    public List<Map<String, Object>> getMerchantListByOrgId(String orgId) {
        return this.MerchantInfoDao.getMerchantListByOrgId(orgId);
    }

    @Override
    public void saveInfo(Map<String, Object> params) {
        //修改添加删除redis的缓存信息
        String merchantId = params.containsKey("customerId") ? params.get("customerId").toString() : "";
        String orgId = params.get("orgId").toString();
        //添加雅智捷店铺信息
        params.put("storeId", StringUtils.isEmpty(merchantId) ? orgId : merchantId);
        //先同步到雅智捷，如果成功再保存
        if (this.yzjRequest.createOrUpdateStore(params)) {
            Integer exiseInfo = MerchantInfoDao.exiseInfo(params);
            if (exiseInfo > 0) {
                MerchantInfoDao.saveInfo(params);
            } else {
                MerchantInfoDao.insertInfo(params);
            }
            stringRedisTemplate.delete("merchant:merchant_info_" + (!StringUtils.isEmpty(merchantId) ? merchantId : orgId));
        }
    }

    @Override
    public Map<String, Object> getTradeBaseInfo(Map<String, Object> param) {
        Map<String, Object> tradeBaseInfo = MerchantInfoDao.getTradeBaseInfo(param);
        String typeInfo;
        if (null != tradeBaseInfo) {
            Long amount = Long.valueOf(tradeBaseInfo.get("amount").toString());
            int type = (int) tradeBaseInfo.get("type");
            switch (type) {
                case 0:
                    amount = MerchantInfoDao.getAmountByOrderSn(tradeBaseInfo.get("orderSn").toString());
                    typeInfo = "提现";
                    break;
                case 1:
                case 10:
                    typeInfo = "商品成交";
                    break;
                case 2:
                    typeInfo = "商品服务费";
                    break;
                case 3:
                    typeInfo = "商品推荐费";
                    break;
                case 4:
                    typeInfo = "商品平台费";
                    break;
                case 5:
                    typeInfo = "开通联盟商家平台费";
                    break;
                case 6:
                    typeInfo = "联盟商家开通";
                    break;
                case 7:
                    typeInfo = "开通加盟代理平台费";
                    break;
                case 8:
                    typeInfo = "加盟代理开通";
                    break;
                case 9:
                    typeInfo = "商品平台费";
                    break;
//                case 10:
//                    typeInfo = "商城商品收益";
//                    break;
                case 11:
                    typeInfo = "提现手续费";
                    break;
                case 12:
                    typeInfo = "提现失败";
                    break;
                case 13:
                    typeInfo = "开通加盟代理服务费";
                    break;
                case 14:
                    typeInfo = "推广佣金";
                    break;
                case 15:
                    typeInfo = "交易手续费";
                    break;
                case 16:
                    typeInfo = "创作奖励";
                    break;
                case 17:
                    typeInfo = "返润佣金";
                    break;
                case 18:
                    typeInfo = "采购";
                    break;
                case 19:
                    typeInfo = "支付抽成";
                    break;
                case 21:
                    typeInfo = "会员开通";
                    break;
                case 31:
                    typeInfo = "体检费支付";
                    break;
                case 32:
                    typeInfo = "体检分佣";
                    break;
                case 33:
                    typeInfo = "体检名额充值";
                    break;
                case 34:
                    typeInfo = "服饰券核销";
                    break;
                case 35:
                    typeInfo = "用户体检";
                    break;
                case 39:
                    typeInfo = "线上体检";
                    break;
                case 40:
                    typeInfo = "线上体检分佣";
                    break;
                case 41:
                    typeInfo = "加盟费";
                    break;
                default:
                    typeInfo = "";
                    break;
            }
            tradeBaseInfo.put("amount", amount);
            tradeBaseInfo.put("typeInfo", typeInfo);
        }
        return tradeBaseInfo;
    }

    //获取订单信息
    @Override
    public Map<String, Object> getOrderInfoByOrderSn(String orderSn) {
        if (orderSn.startsWith("Y")) {
            Map<String, Object> enrollOrder = this.getEnrollOrder(orderSn);
            if (null == enrollOrder) {
                enrollOrder = this.getFromOrder(orderSn);
            }
            enrollOrder.put("orderFlag", "enroll");
            return enrollOrder;
        }
        if (orderSn.startsWith("I")) {
            Map<String, Object> integralOrder = this.integralOrder(orderSn);
            integralOrder.put("orderFlag", "goods");
            return integralOrder;
        }
        Map<String, Object> salerOrder = this.getSalerOrder(orderSn);
        if (null != salerOrder) {
            salerOrder.put("orderFlag", "saler");
            return salerOrder;
        }
        Map<String, Object> goodsOrder = this.getGoodsOrder(orderSn);
        if (null != goodsOrder) {
            goodsOrder.put("orderFlag", "goods");
            return goodsOrder;
        }
        Map<String, Object> vipOrder = this.getVipOrder(orderSn);
        if (null != vipOrder) {
            vipOrder.put("orderFlag", "vip");
            return vipOrder;
        }
//        throw GlobalException.build("无订单数据");
        return new HashMap<>();
    }

    private Map<String, Object> getFromOrder(String orderSn) {
        return MerchantInfoDao.getFromOrder(orderSn);
    }

    private Map<String, Object> integralOrder(String orderSn) {
        return MerchantInfoDao.integralOrder(orderSn);
    }

    @Override
    public Map<String, Object> getSalerOrder(String orderSn) {
        return MerchantInfoDao.getSalerOrder(orderSn);
    }

    @Override
    public Map<String, Object> getGoodsOrder(String orderSn) {
        return MerchantInfoDao.getGoodsOrder(orderSn);
    }

    @Override
    public Map<String, Object> getEnrollOrder(String orderSn) {
        return MerchantInfoDao.getEnrollOrder(orderSn);
    }

    @Override
    public Map<String, Object> getVipOrder(String orderSn) {
        return MerchantInfoDao.getVipOrder(orderSn);
    }

    @Override
    public String storeName(String orgId) {
        return MerchantInfoDao.storeName(orgId);
    }

    @Override
    public String customerStoreName(String orgId, String customerId) {
        return MerchantInfoDao.customerStoreName(orgId, customerId);
    }

    @Override
    public String getEveryMoney(String orgId, String orderSn, Integer type, String userId, boolean ifSales) {
        int role = 1;
        if (ifSales) {
            role = 2;
        }
        Long everyMoney = MerchantInfoDao.getEveryMoney(orgId, orderSn, type, userId, role);
        if (null == everyMoney) {
            everyMoney = 0L;
        }
        //普通用户推荐费不需要加
//        if (type == 2) {
//            Long scoreMoney = MerchantInfoDao.getScoreMoney(orgId, orderSn, 1);
//            if (null != scoreMoney) {
//                everyMoney = everyMoney + scoreMoney;
//            }
//        }
//        if (type == 1) {
//            Long scoreMoney = MerchantInfoDao.getScoreMoney(orgId, orderSn, 0);
//            if (null != scoreMoney) {
//                everyMoney = everyMoney + scoreMoney;
//            }
//        }
        return NumberUtils.fenToYuan(everyMoney);
    }

    @Override
    public String getPlatForm(String orgId) {
        return MerchantInfoDao.getPlatForm(orgId);
    }

    @Override
    public void changeStatus(Map<String, Object> map) {
        // 0：待提交 1：待审核，2：通过，3：打回
        // 20=处理中，30=成功，40=失败
        String id = map.get("customerId").toString();
        String status = "2";
        if ("20".equals(map.get("status").toString())) {
            status = "4";
        } else if (!"30".equals(map.get("status").toString())) {
            status = "3";
        }
        // 判断大麦 或者 联盟商家
        Map<String, Object> result = MerchantInfoDao.getMerchantInfoById(id);
        if (result == null) {
            return;
        }
        if ("2".equals(result.get("type"))) {
            // 审核联盟商城 有cid
            Map<String, Object> temp = new HashMap<>();
            temp.put("customerId", result.get("customerId"));
            temp.put("state", "2".equals(status) ? "1" : "4".equals(status) ? "2" : "0");
            temp.put("goodsStatus", "2".equals(status) ? 1 : 0);
            // 更新联盟商家表 认证状态
            MerchantInfoDao.updateSalerStatus(temp);
        }
        MerchantInfoDao.changeStatus(id, status);
    }

    /**
     * 通过orgId获取orgName
     *
     * @param orgId
     * @return
     */
    @Override
    public String getOrgName(String orgId) {
        String orgName = shopGoodsMapper.getOrgNameByOrgId(orgId);
        if (!StringUtils.isEmpty(orgName)) {
            return orgName;
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("orgcode", orgId);
        reqMap.put("action", "getOrgInfo");
        String url = systemProperties.getUserCenter() + "/WebAPI/BaseInfo.aspx";
        String result;
        try {
            result = httpService.doGet(url, reqMap);
        } catch (URISyntaxException | IOException e) {
            LOGGER.warn(orgId + "机构名称获取失败");
            return null;
        }
        if (!"".equals(result)) {
            Map parse = (Map) JSON.parse(result);
            orgName = (String) parse.get("OrgName");
            if (!StringUtils.isEmpty(orgName)) {
                Map<String, Object> map = new HashMap<>();
                map.put("orgId", orgId);
                map.put("orgName", orgName);
                shopGoodsMapper.updateOrgInfo(map);
                return orgName;
            }
        }
        return null;
    }

    @Override
    public String getDongCustomerPhoneByCustomerId(String dongCustomerId) {
        return MerchantInfoDao.getDongCustomerPhoneByCustomerId(dongCustomerId);
    }

    public void promoterRetreat(Map<String, Object> param) {
        MerchantInfoDao.promoterRetreat(param);
//        MerchantInfoDao.customerRetreat(param);
//        MerchantInfoDao.RetreatPromoterOrder(param);
//        MerchantInfoDao.RetreatPromoterCheck(param);
    }

    @Override
    public List<Map<String, Object>> getsCustomerInfo(Map<String, Object> sp) {
        return MerchantInfoDao.getsCustomerInfo(sp);
    }

    @Override
    public Object getFeeBack(Map<String, Object> ssp) {
        return MerchantInfoDao.getFeeBack(ssp);
    }

    @Override
    public Object getFeeDeal(Map<String, Object> ssp) {
        return MerchantInfoDao.getFeeDeal(ssp);
    }

    @Override
    public void resaveAgent(Map<String, Object> param) {
        MerchantInfoDao.resaveAgent(param);
    }

    @Override
    public void saveCustomPoster(Map<String, Object> params) {
        if (StringUtils.isEmpty(params.get("posterId"))) {
            params.put("posterId", UUID.randomUUID().toString());
            Integer customPosterCount = MerchantInfoDao.getCustomPosterCount(params);
            if (customPosterCount < 5) {
                MerchantInfoDao.addCustomPoster(params);
            } else {
                throw GlobalException.build("海报已达到上限，保存失败");
            }
        } else {
            MerchantInfoDao.editCustomPoster(params);
        }
    }

    @Override
    public Integer getCustomPosterCount(Map<String, Object> params) {
        return MerchantInfoDao.getCustomPosterCount(params);
    }

    @Override
    public void delCustomPoster(Map<String, Object> params) {
        MerchantInfoDao.delCustomPoster(params);
    }
}
